package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.domain.MonitorConfig;
import com.ruoyi.system.domain.MonitorRole;
import com.ruoyi.system.mapper.MonitorConfigMapper;
import com.ruoyi.system.mapper.MonitorRoleMapper;
import com.ruoyi.system.service.MonitorConfigService;
import com.ruoyi.system.service.MonitorRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 监控配置(MonitorConfig)表服务实现类
 *
 * @author dllg-generator
 * @date 2023-05-22 22:40:12
 */
@Service
public class MonitorConfigServiceImpl extends ServiceImpl<MonitorConfigMapper, MonitorConfig> implements MonitorConfigService {

    @Autowired
    private MonitorRoleMapper monitorRoleMapper;
    @Autowired
    private MonitorRoleService monitorRoleService;

    @Override
    public List<MonitorConfig> validList() {
        LambdaQueryWrapper<MonitorConfig> eq = new LambdaQueryWrapper<MonitorConfig>()
                .eq(MonitorConfig::getValid, true)
                .orderByAsc(Arrays.asList(MonitorConfig::getSort, MonitorConfig::getId));
        return baseMapper.selectList(eq);
    }

    @Override
    public List<MonitorConfig> currentList() {
        List<Long> configList = monitorRoleService.selectCurrentList();
        if (CollectionUtils.isEmpty(configList)) {
            return Collections.emptyList();
        }
        LambdaQueryWrapper<MonitorConfig> eq = new LambdaQueryWrapper<MonitorConfig>()
                .in(MonitorConfig::getId, configList)
                .eq(MonitorConfig::getValid, true)
                .eq(MonitorConfig::getEnabled, true)
                .orderByAsc(Arrays.asList(MonitorConfig::getSort, MonitorConfig::getId));
        return baseMapper.selectList(eq);
    }


    @Transactional
    @Override
    public void delete(List<Long> id) {
        MonitorConfig update = new MonitorConfig();
        update.setValid(false);

        LambdaQueryWrapper<MonitorConfig> eq = new LambdaQueryWrapper<MonitorConfig>()
                .in(MonitorConfig::getId, id);
        baseMapper.update(update, eq);

        // 删除关联的权限
        LambdaQueryWrapper<MonitorRole> deleteQuery = new LambdaQueryWrapper<MonitorRole>()
                .in(MonitorRole::getMonitorConfigId, id);
        monitorRoleMapper.delete(deleteQuery);
    }

    @Override
    public void changeEnabled(Long id, Boolean enabled) {
        MonitorConfig update = new MonitorConfig();
        update.setId(id);
        update.setEnabled(enabled);
        baseMapper.updateById(update);
    }
}
